-- UIAwakePearlList
-- Create by chendh
-- 觉醒宝珠列表界面

-- UIAwakePearlList继承自Layer
UIAwakePearlList = class("UIAwakePearlList", function()
    return cc.Layer:create();
end);

function UIAwakePearlList.create()
    return UIAwakePearlList.new();
end

local PAGE_COLUMN   = 4;                -- 最大列数

local tabSkillType  = {-1, 2, 1, 3, 4}; -- 标签对应的显示类型

local campSortRule  = {2, 1, 3, 4};     -- 阵营id排序规则

-- 内部函数声明
local sortSkills;

-- 构造函数
function UIAwakePearlList:ctor()
    -- 初始化
    self:setName("UIAwakePearlList");
    -- 复用编组界面
    local node = cc.CSLoader:createNode("layout/awake/AwakePearlList.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);
    self.pageIndex = 1;

    -- 容器原本的内高
    self.oriHeight = scrollview:getInnerContainerSize().height

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化格子
    self:initGrids(self.node, tabSkillType[self.pageIndex]);

    -- 重绘
    self:redraw(tabSkillType[self.pageIndex]);

    -- 初始化标签页
    self:initTabs();

    -- 适配
    self:resize();
end

-- 初始化标签页
function UIAwakePearlList:initTabs()
    local tabNode = findChildByName(self.node, "CT/tab");
    tabNode:setVisible(true);

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    local tabItem = cc.CSLoader:createNode("layout/tab/tab.csb");
    local widget = replaceNodeWithWidget(tabItem);
    for i = 1, #tabSkillType do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");
        tabImage.camp = tabSkillType[i];

        tabIcon:setVisible(true);
        tabText:setPositionX(tabText:getPositionX() + 1);
        TextStyleM.setTextStyle(tabText, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        tabText:setString(self:getTabText()[i]);
        tabText:setVisible(false);

        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        -- 置灰颜色
        local blendColor = TextStyleM.TEXT_COLOR_BLEND;
        local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

        if i == 1 then
            -- 当前标签页高亮
            tabLight:setVisible(true);
            self.pageIndex = i;
            tabImage:loadTexture(getTabIconPath("red"));

            tabIcon:loadTexture(getSmallHeroIconPath("all"));
        else
            tabLight:setVisible(false);
            tabImage:setColor(blendColor);
            tabText:setColor(blendColor);
            tabImage:loadTexture(getTabIconPath("blue"));

            tabIcon:loadTexture(getCampSmallIconPath(tabSkillType[i]));
        end

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIAwakePearlList:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.2 * (i - 1));
        local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 获取标签文本
function UIAwakePearlList:getTabText()
    local tabTextArray  = {
        getLocStr("tab_text_all"),
        CampM.query(tabSkillType[2], "name"),
        CampM.query(tabSkillType[3], "name"),
        CampM.query(tabSkillType[4], "name"),
        CampM.query(tabSkillType[5], "name"),
    };
    return tabTextArray;
end

-- 点击标签页
function UIAwakePearlList:registerTabTouchEvent(node)
    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local tabImage = node:getChildByName("tab");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除上一个高亮
            local tabNode = findChildByName(self.node, "CT/tab");
            for _, child in pairs(tabNode.rows) do
                if child.index == self.pageIndex then
                    -- 去除高亮
                    local tabLight = findChildByName(child, "light");
                    local tabImage = findChildByName(child, "tab");
                    local tabText  = findChildByName(child, "text");
                    tabLight:setVisible(false);
                    tabImage:setColor(blendColor);
                    tabText:setColor(blendColor);
                end
            end
            -- 设置当前高亮
            local tabLight = findChildByName(node, "light");
            local tabImage = findChildByName(node, "tab");
            local tabText  = findChildByName(node, "text");
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabText:setColor(normalColor);
            self.pageIndex = node.index;

            -- 初始化格子
            self:initGrids(node, tabImage.camp)
            -- 重绘界面
            self:redraw(tabImage.camp);
        end
    end
    tabImage:addTouchEventListener(onClick);
end

-- 适配
function UIAwakePearlList:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化格子
function UIAwakePearlList:initGrids(node, camp)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 1;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 15;
    local bottomHGap  = 50;
    local leftWGap = 10;

    local allPetList = ME.user:getAllPetIds();

    if camp < 0 then
        self.data = allPetList;
    else
        local data = {};

        for _, id in ipairs(allPetList) do
            if CampM.getPetCamp(id) == camp then
                table.insert(data, id);
            end
        end

        self.data = data;
    end

    -- 总数
    local totalCount = #self.data;
    local totalRowNum = math.ceil(totalCount / PAGE_COLUMN);

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    -- 还原容器原本内高
    self.scrollView:setInnerContainerSize(cc.size(self.scrollView:getInnerContainerSize().width, self.oriHeight));

    local itemNode = cc.CSLoader:createNode("layout/sky_city/AirShipSkillItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, totalRowNum, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerItemTouchEvent);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);

        -- 换个背景框
        --local bgImg = findChildByName(child, "bg");
        --bgImg:loadTexture(getFrameBgIconPath("airship_skill"));
    end
end

-- 重绘界面
function UIAwakePearlList:redraw(camp)
    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("awake_pearl"));

    -- 显示副标题
    local subHeadLabel = findChildByName(self.node, "CT/template/subhead");
    --TextStyleM.setSubheadStyle(subHeadLabel);
    subHeadLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
    local kerning = -3;
    if not isChineseLang() then
        kerning = -1;
    end
    TextStyleM.setTextStyle(subHeadLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, kerning, nil, nil, nil, TextStyleM.TEXT_SIZE_MIDDLE, true, 1);

    subHeadLabel:setString(getLocStr("awake_pearl_subhead"));
    subHeadLabel:setVisible(true);

    if not subHeadLabel.initPosY then
        subHeadLabel.initPosY = subHeadLabel:getPositionY();
        subHeadLabel:setPositionY(subHeadLabel.initPosY - 15);
    end

    -- 要显示宝珠的冈布奥列表
    local infoList = {};
    local petList = self.data;

    -- 收集一下宝珠的信息
    for _, petId in pairs(petList) do
        local classId = PetM.query(petId, "pearl");
        local chipId = PetM.query(petId, "chips");
        local info = {
            ["petId"]       = petId,
            ["classId"]     = classId,
            ["campId"]      = CampM.getPetCamp(petId);
            ["icon"]        = ItemM.query(classId, "icon");
            ["amount"]      = ItemM.getAmount(ME.user, classId),
            ["hasOwn"]      = ItemM.getAmount(ME.user, classId) > 0,
            ["canSmelt"]    = AwakeM.canSmeltPearl(petId) == true,
            ["chip_enough"] = ItemM.getAmount(ME.user, chipId) >= AwakeM.calcSmeltCostChipNum(),
        };

        table.insert(infoList, info);
    end

    -- 排序
    table.sort(infoList, sortPearls);
    self.infoList = infoList;

    local totalGridCount = #infoList;
    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            local info = infoList[i];
            --  初始化格子信息
            self:initGridInfo(grid, info);
        end
    end

    -- 屏蔽翻页按钮
    local btnLast = findChildByName(self.node, "CT/btn_last");
    local btnNext = findChildByName(self.node, "CT/btn_next");
    btnNext:setVisible(false);
    btnNext:setVisible(false);
end

-- 对宝珠信息进行排序  按（可熔炼>已有宝珠>碎片数量足够）/ ID排序顺序
function sortPearls(item1, item2)
    if item1["canSmelt"] ~= item2["canSmelt"] then
        return item1["canSmelt"];
    elseif item1["chip_enough"] ~= item2["chip_enough"] then
        return item1["chip_enough"];
    elseif item1["hasOwn"] ~= item2["hasOwn"] then
        return item1["hasOwn"];
    elseif item1["campId"] ~= item2["campId"] then
        return campSortRule[item1["campId"]] < campSortRule[item2["campId"]];
    else
        return item1.classId < item2.classId;
    end
end

--  初始化格子信息
function UIAwakePearlList:initGridInfo(grid, info)
    local bgImg = grid:getChildByName("bg");
    local icon = grid:getChildByName("icon");
    local textLable = grid:getChildByName("text");
    local countLable = grid:getChildByName("count");

    local iconPath = getItemIconPath(tostring(info["icon"]));
    icon:loadTexture(iconPath)
    -- 标记道具ID
    grid.petId = info["petId"];
    grid.classId = info["classId"];

    -- 显示当前已有数量
    if info["amount"] <= 0 then
        setGrayTransMode(bgImg, true);
        bgImg:setOpacity(130);
        icon:setOpacity(180);

        -- 隐藏数量
        countLable:setVisible(false);
    else
        setGrayTransMode(bgImg, false);
        bgImg:setOpacity(255);
        icon:setOpacity(255);

        -- 设置数量
        countLable:setVisible(true);
        TextStyleM.setTextStyle(countLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
        countLable:setString(info["amount"]);
    end

    -- 显示当前是否可熔炼
    if info["canSmelt"] and info["chip_enough"] then
        TextStyleM.setTextStyle(textLable, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_GREEN, true, -2);
        textLable:setString(getLocStr("can_smelt"));
        textLable:setVisible(true);
    else
        textLable:setVisible(false);
    end

    -- 更换下背景框的资源
    bgImg:loadTexture(getFrameBgIconPath("normal"));
end

-- 注册格子点击事件
function UIAwakePearlList:registerItemTouchEvent(node)
    -- 注册图标点击事件
    local bgImg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            require "game/ui/form/item/UIItemCompound"
            UIMgr.getCurrentScene():removeFormByName("UIItemCompound");
            local uiItemCompound = UIItemCompound.create(node.petId, node.classId, nil, nil);
            UIMgr.getCurrentScene():addForm(uiItemCompound);
        end
    end
    bgImg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UIAwakePearlList:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIAwakePearlList");
        elseif eventType == "enter" then

        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIAwakePearlList", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIAwakePearlList" then
            -- 显示界面
            self:setVisible(true);

        elseif para["lose"] == "UIAwakePearlList" then
            -- 隐藏界面
            self:setVisible(false);
        end
    end);

    -- 关注合成成功的事件
    EventMgr.register("UIAwakePearlList", event.DO_COMPOUND, function(args)
        -- 重绘
        self:redraw(tabSkillType[self.pageIndex]);
    end);
end

-- 注册点击事件
function UIAwakePearlList:registerTouchEvent()
    -- 注册确定按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UIAwakePearlList");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 说明按钮
    local btnExchange = findChildByName(self.node, "BT/btn_info");
    btnExchange:setVisible(false);

    -- 隐藏无用按钮
    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);
end


